package com.qfedu.qfoffice.controller;

import com.qfedu.qfoffice.entity.ResponseData;
import com.qfedu.qfoffice.entity.User;
import com.qfedu.qfoffice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录 接口
     * @param no
     * @param pass
     * @return
     */
    @RequestMapping("/login.do")
    @ResponseBody
    public ResponseData login(String no, String pass, HttpSession session){

        ResponseData<Object> responseData = new ResponseData<>();

        User user =  userService.findUserByNo(no);

        if (user==null){ // 该用户不存在
            responseData.setCode(1);
            responseData.setMsg("不存在该用户");
            return responseData;
        }

        if (!user.getPassword().equals(pass)){// 密码错误
            responseData.setCode(1);
            responseData.setMsg("密码或用户错误");
            return responseData;
        }

        session.setAttribute("user", user);
        // 登录成功
        responseData.setCode(0);
        responseData.setMsg("登录成功");

       return responseData;
    }


    /**
     * 判断当前用户是否 登录成功
     * @return
     */
    @RequestMapping("/LoginToJudge.do")
    @ResponseBody
    public ResponseData loginToJudge(HttpSession session){

        ResponseData<Object> responseData = new ResponseData<>();

        User user = (User) session.getAttribute("user");
        if (user!=null){//当前会话恢复登录过
            responseData.setCode(0);
            responseData.setMsg("登录成功");
        }else {
            responseData.setCode(1);
            responseData.setMsg("尚未登录");
        }

        return responseData;
    }

    /**
     * 获取当前用户信息
     * @param session
     * @return
     */
    @RequestMapping("/findByNo.do")
    @ResponseBody
    public ResponseData<User> findCurrentUser(HttpSession session){

        ResponseData<User> userResponseData = new ResponseData<>();
        User user = (User) session.getAttribute("user");

        userResponseData.setCode(0);
        userResponseData.setData(user);

        return userResponseData;
    }
}
